<template>
  <div>
    <!--  理赔款支付页面-->
    <el-form
	  v-loading.fullscreen.lock="fullLoading"
	  element-loading-text="拼命加载中"
      label-width="150px"
      :model="dataForm"
      :rules="rules"
      ref="dataForm"
    >
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>上传理赔款支付情况</span>
        </div>
        <el-row>
          <el-form-item label="付款凭证:" prop="paymentVoucherUploadFlag">
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :disabled="claimSettlement.caseStatus != 3"
              :data="paymentVoucher"
              :file-list="fileList"
              :on-preview="handlePreview"
              :http-request="submitFileUpload"
              :on-remove="handleFileRemove"
              multiple
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="打款支付时间:" prop="payTime">
            <el-date-picker
              v-model="dataForm.payTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择打款支付时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row
          v-if="claimSettlement.caseStatus == 3"
          type="flex"
          justify="center"
        >
          <el-form-item>
            <el-button type="primary" @click="update()" :loading="saveLoading"
              >保存</el-button
            >
          </el-form-item>
        </el-row>
      </el-card>
    </el-form>
	<PreviewFile ref="previewFileRef"></PreviewFile>
  </div>
</template>

<script>
	import PreviewFile from '@/components/previewFile.vue';
export default {
  name: "case-pay",
  data() {
    var validatePaymentVoucherFile = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error("请添加付款凭证"));
      } else {
        callback();
      }
    };
    return {
	  fullLoading:false,
      saveLoading: false,
      paymentVoucher: {
        attachment: "paymentVoucher",
        entityType: "settlementPay",
      },
      fileList: [], // 历史上传的数据,做展示用
      files: [], // 新上传的数据
      deleteFiles: [], // 记录删除的 历史数据
      dataForm: {
        id: "",
        csId: "",
        payProofUrl: "",
        payTime: "",
        paymentVoucherUploadFlag: 0,
      },
      rules: {
        payTime: [
          { required: true, message: "请选择打款支付时间", trigger: "change" },
        ],
        paymentVoucherUploadFlag: [
          {
            required: true,
            validator: validatePaymentVoucherFile,
            trigger: "change",
          },
        ],
      },
    };
  },
  components: {
    // AddOrUpdate
	PreviewFile
  },
  props: ["claimSettlement"],
  activated() {
    console.log("========", this.claimSettlement);
  },
  methods: {
    init: function () {
      this.$http({
        url: this.$http.adornUrl(
          "/claim/settlementpay/info/" + this.claimSettlement.id
        ),
        method: "POST",
      }).then(({ data }) => {
        console.log("data", data);
        if (data && data.code === 0 && data.data) {
          if (data.data.id) {
            this.dataForm = data.data;
            this.dataForm.paymentVoucherUploadFlag = 0;
            // 处理上传文件
            this.fileList = [];
            this.deleteFiles = [];
            this.files = [];
            if (this.dataForm.files) {
              this.dataForm.paymentVoucherUploadFlag =
                this.dataForm.files.length;
              for (let i = 0; i < this.dataForm.files.length; i++) {
				  let filename = this.dataForm.files[i].filePath;
				  const lastIndex = filename.lastIndexOf('_');
				  const dotIndex = filename.lastIndexOf('.');
				  const newName = `${filename.slice(0, lastIndex)}${filename.slice(dotIndex)}`; 
                let obj = {
                  name: newName,
                  url: this.dataForm.files[i].filePath,
                  id: this.dataForm.files[i].id,
                  fileType: this.dataForm.files[i].fileType,
                  attachment: this.dataForm.files[i].attachment,
                };
                this.fileList.push(obj);
              }
            }
          }
        }
      });
    },
    update: function () {
      this.saveLoading = true;
      this.dataForm.csId = this.claimSettlement.id;
      this.dataForm.files = this.files;
      this.dataForm.deleteFiles = this.deleteFiles;
      console.log("this.dataForm", this.dataForm);
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          console.log("valid==", valid);
          this.$http({
            url: this.$http.adornUrl("/claim/settlementpay/save"),
            method: "post",
            data: this.$http.adornData(this.dataForm),
          }).then(({ data }) => {
            this.saveLoading = false;
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.$emit("callBack", null, "refresh");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        } else {
          this.saveLoading = false;
        }
      });
    },

    submitFileUpload: function (req) {
		this.fullLoading = true;
      console.log(req);
      let that = this;
      let reader = new FileReader();
      reader.readAsDataURL(req.file);
      reader.onload = function () {
        let newFileName = that.renameFile(req.file.name, req.file.uid);
        that
          .$http({
            url: that.$http.adornUrl("/migrantWorkers/file/upload"),
            method: "post",
            data: JSON.stringify({ file: reader.result, path: newFileName }),
          })
          .then(({ data }) => {
			  that.fullLoading = false;
            if (data && data.code === 0) {
              let fileParams = {
                fileName: newFileName,
                attachment: req.data.attachment,
                fileType: req.file.type,
                filePath: newFileName,
                entityType: req.data.entityType,
                description: "",
                uid: req.file.uid,
              };
              console.log("gggg", fileParams);
              that.files.push(fileParams);
              that.modifyUploadFlag("upload", req.data.attachment);
			  that.$message.success("上传成功");
            } else if (data && data.msg) {
              that.$message.error(data.msg);
            }
          });
      };
    },
    handlePreview: function (req) {
		this.fullLoading = true;
      console.log("handlePreview", req);
      let that = this;
      let filePath = "";
      let fileType = "";
      if (req.status === "success") {
        filePath = req.url;
        fileType = req.fileType;
      } else if (req.status === "ready") {
        filePath = that.renameFile(req.raw.name, req.raw.uid);
        fileType = req.raw.type;
      }
	  console.log("fileType",fileType)
	  let type = "preview";
	  // if(fileType.indexOf("image") != -1 || fileType.indexOf("pdf") != -1){
		 //  type = "download";
	  // }
      this.$http({
        url: this.$http.adornUrl("/migrantWorkers/file/download"),
        method: "post",
        data: this.$http.adornData(
          {
            path: filePath,
          },
          false,
          "json"
        ),
      }).then(({ data }) => {
		  that.fullLoading = false;
        console.log("data", JSON.stringify(data));
        if (data && data.code === 0) {
			if(type = "preview"){
				//预览
				this.$refs.previewFileRef.showDialog(fileType, data.data, filePath);
			}else{
				that.Base64Util.downloadFile(data.data, filePath, fileType);
			}
        } else if (data && data.msg) {
          that.$message.error(data.msg);
        }
      });
    },
    handleFileRemove: function (req) {
      console.log("handleFileRemove", req);
      let that = this;
      let status = req.status;
      let filePath = "";
      if (status === "success") {
        filePath = req.url;
      } else if (status === "ready") {
        filePath = that.renameFile(req.raw.name, req.raw.uid);
      }
      that
        .$http({
          url: that.$http.adornUrl("/migrantWorkers/file/delete"),
          method: "post",
          data: JSON.stringify({ path: filePath }),
        })
        .then(({ data }) => {
          if (data && data.code === 0) {
            if (status === "success") {
              that.deleteFiles.push(req.id);
              that.modifyUploadFlag("delete", req.attachment);
            } else if (status === "ready") {
              that.files.some((item, i) => {
                // 删除fileList中对应的元素
                if (item.uid === req.raw.uid) {
                  that.modifyUploadFlag("delete", item.attachment);
                  that.files.splice(i, 1);
                }
              });
            }
			that.$message.success("文件删除成功");
          } else if (data && data.msg) {
            that.$message.error(data.msg);
          }
        });
    },
    modifyUploadFlag: function (oper, attachment) {
      console.log("modifyUploadFlag", oper, attachment);
      let flagVal = 0;
      let that = this;
      switch (oper) {
        case "upload":
          flagVal = 1;
          break;
        case "delete":
          flagVal = -1;
          break;
        default:
          flagVal = 0;
          break;
      }
      switch (attachment) {
        case "paymentVoucher":
          that.dataForm.paymentVoucherUploadFlag += flagVal;
          break;
      }
    },
    renameFile: function (originFileName, fileUID) {
      if (originFileName == null || originFileName === undefined) {
        return null;
      }
      let fileNameSplit = originFileName.split(".");
      let fileName = "";
      for (let i = 0; i < fileNameSplit.length - 1; i++) {
        if (i < fileNameSplit.length - 2) {
          fileName = fileName + fileNameSplit[i] + ".";
        } else {
          fileName = fileName + fileNameSplit[i];
        }
      }
      // 跟文件名加上时间
      fileName = fileName + "_" + fileUID;
      let fileExtendName = fileNameSplit[fileNameSplit.length - 1];
      return fileName + "." + fileExtendName;
    },
  },
};
</script>

<style scoped>
</style>
